<?php

	/**
	 * Defines a class to be used for Datetime Data Typing with PHP
	 * 
	 * @author Pablo Santiago Sánchez <phackwer@gmail.com>
	 * @copyright Copyright (c) 2008, Pablo Santiago Sánchez
	 * @license http://opensource.org/licenses/bsd-license.php BSD License
	 * @package pop
	 * @subpackage datatypes
	 */

	/**
	 * Class used to handle date and time fields.
	 * Only YYYY-MM-DD HH:MM:SS format allowed.
	 * 
	 * @package pop
	 * @subpackage datatypes
	 */
	class PDatetime extends PTypeBase
	{
		/**
		 * Constructor, in which you must inform the default date and time.
		 * If none is informed, it uses NOW as default
		 * @param string $defaultval Default value. Must be a valid date and time (YYYY-MM-DD HH:MM:SS)
		 */
		public function __construct($defaultval = NOW)
		{
			$this->__set("value", $defaultval);
			$this->defaultval 	= $defaultval;
		}

		/**
		 * Magic method used to set the value and check if it's valid
		 * @param string $name name of the value
		 * @param string $value value itself
		 * @return bool 
		 */
		public function __set($name, $value)
		{
			if ($value === "")
				$value = null;

			if (!is_null($value))
			{
				$check = explode(" ",$value);
				$date = explode("-",$check[0]);
				$time = explode(":",$check[1]);

				//filter time, because on MSSQL it may come with miliseconds
				if ($time[2] && strstr($time[2], "."))
				{
					$time[2] = substr($time[2],0,2);
					$value = substr($value, 0, strpos($value, "."));
				}

				if ($name != "value")
				{
					throw new Exception("This attribute cannot be set");
				}
				else if (!$date[1] || !$date[2] || !$date[0] || !checkdate($date[1],$date[2],$date[0]))
				{
					throw new Exception("This attribute must be a valid datetime.\nName: <font color=#FF0000>".$name."</font>\nValue: <font color=#FF0000>".$value."</font>");
				}
				else if (!ctype_digit((string)str_replace(array(" ",":","-"),"",$value)) || !$time[0] || !$time[1] || $time[0] < 0 || $time[1] < 0 || $time[1] > 59)
				{
					throw new Exception("This attribute must be a valid time.\nName: <font color=#FF0000>".$name."</font>\nValue: <font color=#FF0000>".$value."</font>");
				}
				else
				{
					$this->$name = $value;
					return true;
				}
			}
			else if (!is_null($this->defaultval))
			{
				throw new Exception("This attribute must be a valid time.\nName: <font color=#FF0000>".$name."</font>\nValue: <font color=#FF0000>".$value."</font>");
			}
			else
			{
				$this->$name = $value;
				return true;
			}
		}
	}

?>
